﻿// ********************* DC *******************************
var Dc = function() {
	var self = this;
	var call = new DcCall();
	var el = $("#infopanel").append("<ol id='dc_list' class='main_list'></ol>");
	call.Load(function(item) {
		self.Append(item);
	});
	$('#dc_edit').show().button().click(function() { self.EnterEditMode(); return false; });
	$('#dc_add').show().button().hide();
	
	this.Append = function(data) {
		var li = $('<li class="ui-state-default" title="' + data.address + '"><img src="img/datacenter-icon.gif" /><div>' + data.name + '</div></li>')
		.appendTo('#dc_list').data('data', data);
		li.click(function () {
			self.ShowRacks(li);
		}).tooltip();
	};
	
	this.ShowRacks = function(li) {
		console.log(li.data('data'));
		var rack = new Rack(li.data('data'));
			rack.DcChanged = function(dc) {
				li.data('data', dc);
			};
	};
	
	this.AppendEditButtons = function(item) {
		$("<a href='#' style='float:right; padding-top:10px;padding-bottom:10px;top:-2px;'></a>").button({ icons: { primary: "ui-icon-pencil" }, text: false }).appendTo(item).click(function () { self.Edit(item); });
		$("<a href='#' style='float:right; padding-top:10px;padding-bottom:10px;top:-20px;'></a>").button({ icons: { primary: "ui-icon-close" }, text: false }).appendTo(item).click(function () { self.Remove(item); });
	};
	
	this.EnterEditMode = function () {
		console.log("enter edit mode");
		$('#dc_add').show().click(self.Add);
		$('#dc_list li').each(function (index, item) {
			item = $(item);
			item.unbind('click');
			self.AppendEditButtons(item);
		});
		$('#dc_edit').button('option', 'label', 'Finish editing').click(self.LeaveEditMode);
		return false;
	};
	
	this.LeaveEditMode = function () {
		$('#dc_add').hide();
		$('#dc_edit').unbind('click').button('option', 'label', 'Edit mode').click(self.EnterEditMode);
		$('#dc_list li .pencil').remove();
		$('#dc_list a').remove();
		$('#dc_list li').each(function (index, item) {
			$(item).click(function () { var rack = new Rack($(item).data('data')); });
		});
		return false;
	};
	
	this.Remove = function (item) {
		item = $(item);
		var call = new DcCall();
		call.Remove(item.data('data'), function() {
			item.remove();
		});
		return false;
	};
	
	this.Edit = function (item) {
		var form = new DcForm('edit');
		form.Empty();
		form.Load($(item).data('data'));
		form.Show(function(data) {
			item.data('data', data);
			item.attr('title', data.address).children('div').empty().append('<div>' + data.name + '</div>');
			item.tooltip();
		});
		return false;
	};
	
	this.Add = function () {
		var form = new DcForm('add');
		form.Empty();
		form.Show(function(data) {
			self.AppendEditButtons(self.Append(data).unbind('click'));
		});
		return false;
	};
};

// ***************************** DC form ********************************
var DcForm = function(mode) {
	this.mode = mode;
}
DcForm.prototype.id = function(value) {
	if (typeof value == 'undefined') {
		return $('#form_dc_id').val();
	} else {
		$('#form_dc_id').val(value);
	}
};
	
DcForm.prototype.name = function(value) {
	if (typeof value == 'undefined') return $('#form_dc_name').val();
	else $('#form_dc_name').val(value);
}
	
DcForm.prototype.address = function(value) {
	if (typeof value == 'undefined') return $('#form_dc_address').val();
	else $('#form_dc_address').val(value);
}
	
DcForm.prototype.power = function(value) {
	if (typeof value == 'undefined') return $('#form_dc_power').val();
	else $('#form_dc_power').val(value);
}
	
DcForm.prototype.notes = function(value) {
	if (typeof value == 'undefined') return $('#form_dc_notes').val();
	else $('#form_dc_notes').val(value);
}
	
DcForm.prototype.Empty = function() {
	this.id('');
	this.name('');
	this.address('');
	this.power('');
	this.notes('');
};

DcForm.prototype.Load = function(data) {
	this.id(data.id);
	this.name(data.name);
	this.address(data.address);
	this.power(data.power);
	this.notes(data.notes);
}
	
DcForm.prototype.Show = function(callback) {
	var title = (this.mode == 'add') ? 'Add new datacenter' : 'Edit datacenter info';
	var self = this;
	$('#dc_edit_form').dialog({ 'title': title, modal: true, width: 'auto', height: 'auto', buttons: {
		'Save': function () {
			var opts = {
				'mode': self.mode,
				name: self.name(),
				address: self.address(),
				power: self.power(),
				notes: self.notes()
			};
			if (self.mode == 'edit') {
				opts.id = self.id();
			}
			var call = new DcCall();
			call.Save(self.mode, opts, function(data) {
				if (callback) callback(data);
				$('#dc_edit_form').dialog('close');
			});
		},
		'Cancel': function () {
			$(this).dialog('close');
		}
	}});
};

// *************************** DC full *********************************
var DcFull = function() {
	this.Load();
}

DcFull.prototype.Load = function() {
	var self = this;
	var call = new DcCall();
	$('.dc_td_edit').unbind('click');
	$('.dc_td_remove').unbind('click');
	$('#tab-datacenters tbody').empty();
	call.Load(function(item) {
		$('<tr><td>' + item.name + '</td><td>' + item.address + '</td><td>' + item.power + '</td><td>' + item.notes + '</td><td class="dc_td_edit">&nbsp;</td><td class="dc_td_remove">&nbsp;</td></tr>').appendTo('#tab-datacenters tbody').data('data', item);
	},
	function() {
		$("<a href='#'></a>")
		.button({ icons: { primary: "ui-icon-pencil" }, text: false })
		.appendTo($('.dc_td_edit')).click(function() {
			self.Edit($(this).parent().parent().data('data'));
		});
		$("<a href='#'></a>")
		.button({ icons: { primary: "ui-icon-close" }, text: false })
		.appendTo($('.dc_td_remove')).click(function() {
			self.Remove($(this).parent().parent().data('data'));
		});
	});
};

DcFull.prototype.Edit = function(data) {
	var self = this;
	var form = new DcForm('edit');
	form.Empty();
	form.Load(data);
	form.Show(function(data) {
		self.Load();
	});
}

DcFull.prototype.Add = function() {
	var self = this;
	var form = new DcForm('add');
	form.Empty();
	form.Show(function(data) {
		self.Load();
	});
}

DcFull.prototype.Remove = function(data) {
	var self = this;
	var call = new DcCall();
	call.Remove(data, function() {
		self.Load();
	});
}

// ******************** DC Call ***********************************
var DcCall = function() {
};

DcCall.prototype.Load = function(callback, finish_callback) {
	$.ajax({url: '/call.aspx?source=dc', success: function(data) {
		var cnt = data.length;
		console.log('loaded');
		if (cnt == 0 && finish_callback) finish_callback();
		else {
			$.each(data, function(index, item) {
				if (callback) callback(item);
				cnt--;
				if (cnt == 0) {
					if (finish_callback) finish_callback();
				}
			});
		}
	}, error: function(obj, error, errorThrown) {
		console.log(obj.responseText);
		console.log(error);
		console.log(errorThrown);
	}});
};

DcCall.prototype.GetList = function(callback) {
	$.getJSON('/call.aspx?source=dc&mode=dictionary', function (data) {
		if (callback) callback(data);
	});
}

DcCall.prototype.Save = function(mode, data, callback) {
	data.mode = mode;
	data.source = 'dc';
	$.getJSON('/call.aspx?', data, function (result) {
		if (result.result == 'RESULT_OK') {
			var item = {
				name: data.name,
				address: data.address,
				power: data.power,
				notes: data.notes
			};
			item.id = (mode == 'add') ? result.id : data.id;
			if (callback) callback(item);
		} else {
			Warning('Error during saving of the datacenter', result.result);
		}
	});
}

DcCall.prototype.Remove = function(data, callback) {
	Confirm('Are you sure to remove datacenter ' + data.name + ' and all racks and servers within it?', function() {
		$.getJSON('/call.aspx', { source: 'dc', mode: 'remove', id: data.id }, function (result) {
			if (result.result == 'RESULT_OK') {
				if (callback) callback();
			} else {
				Warning('Error during removing of ' + data.name, result.result);
			}
		});
	});
}

DcCall.prototype.Resize = function(dc, width, height, callback) {
	$.getJSON('/call.aspx?', {source: 'dc', mode: 'resize', id: dc.id, 'width': width, 'height': height}, function(result) {
		if (result.result == 'RESULT_OK') {
			if (callback) callback();
		} else {
			Warning('Error during resizing datacenter container', result.result);
		}
	});
}

DcCall.prototype.MoveEntrance = function(id, top, left, callback) {
	$.getJSON('/call.aspx?', {source: 'dc', mode: 'move_entrance', id: id, 'top': top, 'left': left}, function(result) {
		if (result.result == 'RESULT_OK') {
			if (callback) callback();
		} else {
			Warning('Error during moving datacenter entrance', result.result);
		}
	});
}
// ********************** DC select ****************************
var DcSelect = function(control) {
	var self = this;
	this.control = control;
	this.dcs = [];
	this.selected = 0;
	this.change_callback;
};

DcSelect.prototype.SelectedName = function() {
	return this.control.next().val();
};

DcSelect.prototype.SelectedValue = function() {
	for (var i in this.dcs) {
		if (this.dcs[i].name == this.SelectedName()) return this.dcs[i].id;
	}
	return 0;
};

DcSelect.prototype.Load = function(selected) {
	var self = this;
	if (selected) self.selected = selected;
	var call = new DcCall();
	call.GetList(function(data) {
		self.dcs = data;
		self.control.combobox('destroy').empty();
		self.control.append('<option value="0">--</option>');
		$.each(data, function (index, item) {
			self.control.append('<option value="' + item.id + '">' + item.name + '</option>');
		});
		self.control.combobox({strict: true, change: function(index, value) {
			if (self.change_callback) self.change_callback(index, value);
		}});
		self.Select(self.selected);
	});
};

DcSelect.prototype.onChange = function(callback) {
	this.change_callback = callback;
}

DcSelect.prototype.Select = function(value) {
	var self = this;
	self.selected = value;
	if (self.dcs.length > 0) {
		if (!value) {
			self.control.val(0);
			self.control.next().val('--');
		} else if (isNaN(parseInt(value))) {
			for (var i in self.dcs) {
				var item = self.dcs[i];
				if (item.name == value) {
					self.control.val(item.id);
					self.control.next().val(item.name);
					break;
				}
			}
		} else {
			for (var i in self.dcs) {
				var item = self.dcs[i];
				if (item.id == value) {
					self.control.val(item.id);
					self.control.next().val(item.name);
					break;
				}
			}
		}
	}
};
